// miniprogram/pages/mine/mine.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    loginStatus: '点击登录',
    avatarUrl: './user-unlogin.png',
    userInfo: {},
    hasUserInfo: false,
    logged: false,
    takeSession: false,
    requestResult: '',
    canIUseGetUserProfile: false,
    // canIUseOpenData: wx.canIUse('open-data.type.userAvatarUrl'), // 如需尝试获取用户信息可改为false
    canIUseOpenData: false, // 如需尝试获取用户信息可改为false

    modifyName: '',
    isShowNickName: false,
    userInfo: {},
    progress: 0,
    isShowGroupPop: false,
    groups: ['冲锋组', '基石组']
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let hasUserInfo = wx.getStorageSync('hasUserInfo');
    console.log('hasUserInfo', hasUserInfo)
    if (hasUserInfo) {
      let avatarUrl = wx.getStorageSync('avatarUrl');
      let userInfo = wx.getStorageSync('userInfo');
      let nickName = wx.getStorageSync('nickName')
      let isCoach = wx.getStorageSync('isCoach')
      this.setData({
        avatarUrl: avatarUrl,
        userInfo: userInfo,
        hasUserInfo: true,
        loginStatus: nickName.length > 0 ? nickName : '点击登录',
        isCoach: isCoach
      })
    } else {
      if (wx.getUserProfile) {
        this.setData({
          canIUseGetUserProfile: true,
        })
      }
    }
  },
  getUserProfile() {
    // 推荐使用wx.getUserProfile获取用户信息，开发者每次通过该接口获取用户个人信息均需用户确认，开发者妥善保管用户快速填写的头像昵称，避免重复弹窗
    wx.getUserProfile({
      desc: '展示用户信息', // 声明获取用户个人信息后的用途，后续会展示在弹窗中，请谨慎填写
      success: (res) => {
        console.log(res)
        this.setData({
          avatarUrl: res.userInfo.avatarUrl,
          userInfo: res.userInfo,
          hasUserInfo: true,
          loginStatus: res.userInfo.nickName
        })
        try {
          wx.setStorageSync('avatarUrl', res.userInfo.avatarUrl)
          wx.setStorageSync('userInfo', res.userInfo)
          wx.setStorageSync('hasUserInfo', true)
          wx.setStorageSync('nickName', res.userInfo.nickName)
        } catch (e) {
          console.log('写入用户信息发生错误')
        }

        wx.showLoading({
          title: '登陆中...',
        })
        wx.cloud.callFunction({
          name: 'login',
          data: {
            'avatarUrl': res.userInfo.avatarUrl,
            'nickName': res.userInfo.nickName
          },
          success: res => {
            wx.hideLoading()
            console.log('[云函数] [login] 调用成功', res)
            this.setData({
              loginStatus: res.result.data.nickName,
              isCoach: res.result.data.isCoach
            })
            try {
              wx.setStorageSync('nickName', res.result.data.nickName)
              wx.setStorageSync('isCoach', res.result.data.isCoach)
              wx.setStorageSync('openid', res.result.data._openid)
            } catch (e) {
              console.log('写入用户信息发生错误')
            }
          },
          fail: err => {
            wx.hideLoading()
            console.error('[云函数] [login] 调用失败', err)
          }
        })
        this.handleTotal()
      }
    })
  },

  onGetUserInfo: function (e) {
    if (!this.data.logged && e.detail.userInfo) {
      this.setData({
        logged: true,
        avatarUrl: e.detail.userInfo.avatarUrl,
        userInfo: e.detail.userInfo,
        hasUserInfo: true,
      })
    }
  },
  bindViewTap() {
    wx.cloud.callFunction({
      name: 'setUser',
      data: {
        avatarUrl: 'https://636c-cloud1-5gyjce1s108fc6f7-1327422451.tcb.qcloud.la/avatarUrls/oHyYh7W1IfIi5RiCIp6axpqMQYNk.png?t=1720444490764'
      },
      success: res=> {
        console.log('setUser 云函数调用',res)
      }
    });
  },
  onChooseAvatar(e) {
    let that = this
    var aa = e.detail.avatarUrl;
    let _openid = wx.getStorageSync('openid')
    console.log('aa', aa, '_openid', _openid)
    wx.cloud.uploadFile({
      cloudPath:'avatarUrls/'+_openid+'.png',
      filePath: aa,
      success: res => { 
        wx.cloud.getTempFileURL({
          fileList: [res.fileID], 
          success: ress => {
            let url = ress.fileList[0].tempFileURL+'?t='+new Date().getTime();
            wx.setStorageSync('avatarUrl', url)
            that.setData({
              avatarUrl: url
            }, () => {
              console.log('获取到http格式的文件', this.data.avatarUrl)
              // 同步到数据库
              wx.cloud.callFunction({
                name: 'setUser',
                data: {
                  avatarUrl: this.data.avatarUrl
                },
                success: res => {
                  console.log('更新成功')
                },
                fail: err => {
                  console.error(err)
                }
              })
            })
          },
          fail: console.error
        })
 
      },
      fail: err => {
        console.log("上传云存储失败", err)
      }
    })
 
  },
  onGetOpenid: function () {
    let _openid = wx.getStorageSync('openid')
    if (_openid) {
      this.logout()
    } else {
      this.getUserProfile()
    }
  },

  checkIsLogin: function () {
    let _openid = wx.getStorageSync('openid')
    if (!_openid) {
      wx.showModal({
        title: '登陆',
        content: '你还未登陆，请先登陆！',
        confirmText: '确认',
        cancelText: '取消',
        success: res => {
          console.log(res)
          if (res.confirm) {
            this.getUserProfile()
          }
        }
      })
      return false
    }
    return true
  },

  logout: function () {
    let _openid = wx.getStorageSync('openid')
    if (_openid) {
      wx.showModal({
        title: '退出登陆',
        content: '确认退出登陆吗？',
        confirmText: '确认',
        cancelText: '取消',
        success: res => {
          if (res.confirm) {
            this.setData({
              hasUserInfo: false,
              loginStatus: '点击登录',
              avatarUrl: './user-unlogin.png',
              userInfo:{},
              isCoach: false
            })
            wx.setStorageSync('nickName', '')
            wx.setStorageSync('hasUserInfo', false)
            wx.setStorageSync('isCoach', '')
            wx.setStorageSync('openid', '')
            wx.setStorageSync('memberInfo', {})
          }
        }
      })
    }
  },

  onRequestCoach: function () {
    if (!this.checkIsLogin()) {
      return
    }
    wx.showModal({
      title: '申请教练',
      content: '申请教练，只针对教练组成员，确认申请吗？',
      confirmText: '确认',
      cancelText: '取消',
      success: function (res) {
        if (res.confirm) {
          wx.cloud.callFunction({
            name: 'coach',
            data: {},
            success: res => {
              console.log(res)
              if (res.result.success) {
                wx.showModal({
                  title: '申请教练成功',
                  content: res.result.message,
                  confirmText: '我知道了',
                  showCancel: false,
                  success: function (res) {
                  }
                })
              } else {
                wx.showModal({
                  title: '申请教练失败',
                  content: res.result.message,
                  confirmText: '我知道了',
                  showCancel: false,
                  success: function (res) {
                  }
                })
              }

            },
            fail: err => {
            }
          })
        } else if (res.cancel) {

        }
      }
    })
  },

  onRequestNickName: function () {
    this.setData({
      isShowNickName: false
    })
  },

  onClickModifyName: function () {
    if (!this.checkIsLogin()) {
      return
    }
    this.setData({
      isShowNickName: true
    })
  },

  onClickCheckAbsence: function () {
    if (!this.checkIsLogin()) {
      return
    }
    wx.navigateTo({
      url: './absence/list/index',
    })
  },
  onClickNameCancle: function () {
    this.setData({
      isShowNickName: false
    })
  },
  onClickExcelByMonth: function (contentArr) {
    wx.showLoading({
      title: '加载中...',
    })
    wx.cloud.callFunction({
      name: 'getMonthExcel',
      data: {
      },
      success: fdetail => {
        wx.hideLoading()
        console.log(fdetail.result);
        console.log(fdetail.result.fileID);
 
        var downloadTask = null;//下载进度监听器
        downloadTask = wx.cloud.downloadFile({
          fileID: fdetail.result.fileID,
          success: function (res) {
             //提示框
          wx.showToast({
            title: '文件下载成功',
            icon:"success",
            duration:2000
          })

          //打开文件
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            fileType: 'xlsx',
            showMenu: true,
            success: function (res) {
              console.log('打开文档成功',res)
            }
          })
          },
          fail: function (result){
            console.log(result);
          }
        })
        downloadTask.onProgressUpdate((res) => {
          console.log(res.progress)
          this.setData({
            progress: res.progress
          })
        })
      },
      fail: function (res) {
        wx.hideLoading()
        console.log(res);
      }
    })
  },
  onClickExcel: function (contentArr) {
    wx.showLoading({
      title: '加载中...',
    })
    wx.cloud.callFunction({
      name: 'getWeekExcel',
      data: {
      },
      success: fdetail => {
        wx.hideLoading()
        console.log(fdetail.result);
        console.log(fdetail.result.fileID);
 
        var downloadTask = null;//下载进度监听器
        downloadTask = wx.cloud.downloadFile({
          fileID: fdetail.result.fileID,
          success: function (res) {
             //提示框
          wx.showToast({
            title: '文件下载成功',
            icon:"success",
            duration:2000
          })

          //打开文件
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            fileType: 'xlsx',
            showMenu: true,
            success: function (res) {
              console.log('打开文档成功',res)
            }
          })
          },
          fail: function (result){
            console.log(result);
          }
        })
        downloadTask.onProgressUpdate((res) => {
          console.log(res.progress)
          this.setData({
            progress: res.progress
          })
        })
      },
      fail: function (res) {
        wx.hideLoading()
        console.log(res);
      }
    })
  },
  onClickNameConfirm: function () {
    this.setData({
      isShowNickName: false
    })
    console.log(this.data.modifyNickName)
    wx.cloud.callFunction({
      name: 'modifyNickName',
      data: {
        nickName: this.data.modifyNickName
      },
      success: res => {
        console.log(res)
        if (res.result.success) {
          this.setData({
            loginStatus: res.result.data.nickName,
          })
          try {
            wx.setStorageSync('nickName', res.result.data.nickName)
          } catch (e) {
            console.log('写入用户信息发生错误')
          }
          wx.showModal({
            content: res.result.message,
            confirmText: '我知道了',
            showCancel: false,
            success: function (res) {
            }
          })
        } else {
          wx.showModal({
            content: res.result.message,
            confirmText: '我知道了',
            showCancel: false,
            success: function (res) {
            }
          })
        }

      },
      fail: err => {
      }
    })
  },
  onClickApprove: function () {
    if (!this.checkIsLogin()) {
      return
    }
    wx.navigateTo({
      url: '../card/list/list',
    })
  },
  onClickMyCard: function () {
    if (!this.checkIsLogin()) {
      return
    }
    wx.navigateTo({
      url: '../card/mycard/myCard',
    })
  },
  onClickAbsence: function () {
    if (!this.checkIsLogin()) {
      return
    }
    wx.navigateTo({
      url: './absence/index',
    })
  },
  onClickActivity: function () {
    console.log('onClickActivity')
    if (!this.checkIsLogin()) {
      return
    }
    wx.navigateTo({
      url: './activity/list/index',
    })
  },
  onClickGroup: function () {
    this.setData({
      isShowGroupPop: true
    })
  },
  onGroupConfirm(event) {
    const { picker, value, index } = event.detail;
    console.log(`当前值：${value}, 当前索引：${index}`);
    this.setData({
      isShowGroupPop: false
    })

    wx.showLoading({
      title: '加载中...',
    })
    let _openid = wx.getStorageSync('openid')
    wx.cloud.callFunction({
      name: 'updateUserGroup',
      data: {
        'groupName': value,
        'groupIndex': index == 0 ? 'AB' : 'C',
        'openid':_openid
      },
      success: res => {
        wx.hideLoading()
        wx.showToast({
          title: '设置分组成功',
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '设置分组失败',
        })
      }
    })
  },

  onGroupCancel() {
    this.setData({
      isShowGroupPop: false
    })
  },
  onClickOpenActivity(){
    wx.showLoading({
      title: '加载中...',
    })
    let _openid = wx.getStorageSync('openid')
    wx.cloud.callFunction({
      name: 'openActivity',
      data: {
        'openid':_openid
      },
      success: res => {
        console.log(res)
        wx.hideLoading()
        wx.showToast({
          title: res.result.message,
        })
      },
      fail: err => {
        wx.hideLoading()
        wx.showToast({
          title: '操作失败',
        })
      }
    })
  },
  onClickMember: function () {
    if (!this.checkIsLogin()) {
      return
    }
    wx.navigateTo({
      url: '../member/member',
    })
  },
  onClickScan: function () {
    wx.scanCode({
      success: (res) => {
        console.log("扫码结果", res);
        let avatarUrl = wx.getStorageSync('avatarUrl');
        let nickName = wx.getStorageSync('nickName')
        wx.showLoading({
          title: '加载中...',
        })
        wx.cloud.callFunction({
          name: 'checkInActivity',
          data: {
            nickName: nickName,
            result: res.result,
            avatarUrl: avatarUrl
          },
          success: res => {
            console.log(res)
            wx.hideLoading()
            wx.showModal({
              content: res.result.message,
              confirmText: '我知道了',
              showCancel: false,
              success: function (res) {
              }
            })
          },
          fail: err => {
            wx.hideLoading()
          }
        })
      },
      fail: (res) => {
        console.log(res);
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.getTabBar().init();
    let _openid = wx.getStorageSync('openid')
    if (!_openid) return
    wx.cloud.callFunction({
      name: 'getUser',
      data: {},
      success: res => {
        console.log(res)
        const userInfo = res.result.userInfo;
        this.setData({
          avatarUrl: userInfo.avatarUrl,
          userInfo: userInfo,
          hasUserInfo: true,
          loginStatus: userInfo.nickName.length > 0 ? userInfo.nickName : '点击登录',
          isCoach: userInfo.isCoach
        });
        wx.setStorageSync('avatarUrl', userInfo.avatarUrl)
          // wx.setStorageSync('userInfo', userInfo)
          // wx.setStorageSync('hasUserInfo', true)
          // wx.setStorageSync('nickName', userInfo.nickName)

      },
      fail: err => {
        console.error(err)
      }
    })
    // 获取总积分
    this.handleTotal()

  },
  // 获取总积分
  handleTotal() {
    wx.cloud.callFunction({
      name: 'getUserInfo',
      data: {},
      success: res => {
        console.log(res)
        const userData = res.result.userInfo;
        const {point,distance,time,calorie } = userData;
        const userInfo = Object.assign(this.data.userInfo,{point,distance,time,calorie})
        this.setData({
          userInfo: userInfo,
        });
      },
      fail: err => {
        console.error(err)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})